//
//  BuyAiCountViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import LeanCloud
//购买次数
class BuyAiCountViewModel : AiActViewModel {
    @Published var items = [BuyCountBean]()
    @Published var selectedIndex: Int = 0
    @Published var status = ""
    @Published var loadDialog = true
    
    func getData(_ isRefresh: Bool = false) {
        requestList(isRefresh: isRefresh) {
            let query = LCQuery(className: "AiCountConfig2")
            query.whereKey("hide", .equalTo(false))
            query.whereKey("sort", .ascending) //升序
            let list =  try await LeancloudManager.instance.getList(query: query, modeType: BuyCountBean.self)
            try check(!isRefresh || !list.isEmpty, "暂无数据")
            return list
        } suc: { diarys in
            self.status = ""
            self.items.append(contentsOf: diarys)
        } fail: {
            self.status = $0.message
        }
    }
    
    func getProductId() -> String {
        return items[selectedIndex].productId ?? ""
    }
    
    func getBean() -> BuyCountBean {
        return items[selectedIndex]
    }
    
    func doBuy(productID: String, bean: BuyCountBean) {
        request {
            try await InviteRewardUtils.doBuyCount(userManager.getUser()?.inviteUserId, bean.title ?? "",bean.inviteCount ?? 0)
            //预先购买记录
            try await retry(maxRetries: 5, retryDelayMillis: 200) {
                var record = VipPrePayRecordBean()
                record.userId = userManager.getUserId()
                record.userName = userManager.getName()
                record.channel = "apple"
                record.payType = bean.title
                record.json = toJson(bean)
                try await LeancloudManager.instance.save(todo: record)
            }
            let count = (bean.count ?? 0) + (bean.giftCount ?? 0)
            showLog("购买次数：\(count)")
            AiChatExt.doAiChatCount(Double(count))
            return true
        } suc: { _ in
            showToast("购买成功")
            hideLoadPopup()
        } fail: {_ in
            hideLoadPopup()
        }
    }
    
}
